const io = require('socket.io-client');
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

class ChatClient {
    constructor(serverUrl = 'http://localhost:3002') {
        this.serverUrl = serverUrl;
        this.socket = null;
        this.user = null;
    }

    // 连接到服务器
    async connect() {
        this.socket = io(this.serverUrl);
        
        // 设置事件监听器
        this.socket.on('user_joined', this.handleUserJoined.bind(this));
        this.socket.on('chat_message', this.handleChatMessage.bind(this));
        this.socket.on('private_message', this.handlePrivateMessage.bind(this));
        this.socket.on('message_history', this.handleMessageHistory.bind(this));
        this.socket.on('unread_messages', this.handleUnreadMessages.bind(this));
        this.socket.on('user_left', this.handleUserLeft.bind(this));
    }

    // 注册新用户
    async register(username, password) {
        try {
            const response = await axios.post(`${this.serverUrl}/auth/register`, {
                username,
                password
            });
            this.user = response.data.user;
            return response.data;
        } catch (error) {
            throw error.response.data;
        }
    }

    // 用户登录
    async login(username, password) {
        try {
            const response = await axios.post(`${this.serverUrl}/auth/login`, {
                username,
                password
            });
            this.user = response.data.user;
            return response.data;
        } catch (error) {
            throw error.response.data;
        }
    }

    // 加入聊天
    joinChat() {
        if (!this.user) {
            throw new Error('请先登录');
        }
        this.socket.emit('user_join', this.user.username);
    }

    // 发送群聊消息
    sendGroupMessage(message) {
        if (!this.socket) {
            throw new Error('未连接到服务器');
        }
        this.socket.emit('chat_message', { message });
    }

    // 发送私聊消息
    sendPrivateMessage(to, message) {
        if (!this.socket) {
            throw new Error('未连接到服务器');
        }
        this.socket.emit('private_message', { to, message });
    }

    // 上传文件
    async uploadFile(filePath) {
        try {
            const form = new FormData();
            form.append('file', fs.createReadStream(filePath));

            const response = await axios.post(`${this.serverUrl}/upload`, form, {
                headers: form.getHeaders()
            });
            return response.data;
        } catch (error) {
            throw error.response.data;
        }
    }

    // 标记消息为已读
    markMessageAsRead(messageId) {
        if (!this.socket) {
            throw new Error('未连接到服务器');
        }
        this.socket.emit('message_read', { messageId });
    }

    // 删除消息
    deleteMessage(messageId) {
        if (!this.socket) {
            throw new Error('未连接到服务器');
        }
        this.socket.emit('delete_message', { messageId });
    }

    // 事件处理函数
    handleUserJoined(data) {
        console.log('用户加入:', data);
    }

    handleChatMessage(data) {
        console.log('群聊消息:', data);
    }

    handlePrivateMessage(data) {
        console.log('私聊消息:', data);
    }

    handleMessageHistory(data) {
        console.log('消息历史:', data);
    }

    handleUnreadMessages(data) {
        console.log('未读消息:', data);
    }

    handleUserLeft(data) {
        console.log('用户离开:', data);
    }

    // 断开连接
    disconnect() {
        if (this.socket) {
            this.socket.disconnect();
            this.socket = null;
        }
    }
}

// 使用示例
async function example() {
    const client = new ChatClient();
    
    try {
        // 连接服务器
        await client.connect();
        
        // 注册新用户
        await client.register('testuser', 'password123');
        
        // 或者登录已有用户
        await client.login('testuser', 'password123');
        
        // 加入聊天
        client.joinChat();
        
        // 发送群聊消息
        client.sendGroupMessage('Hello, everyone!');
        
        // 发送私聊消息
        client.sendPrivateMessage('otheruser', 'Hi there!');
        
        // 上传文件
        const fileInfo = await client.uploadFile('test.txt');
        console.log('文件上传成功:', fileInfo);
        
        // 标记消息已读
        client.markMessageAsRead('messageId123');
        
        // 删除消息
        client.deleteMessage('messageId123');
        
        // 5秒后断开连接
        setTimeout(() => {
            client.disconnect();
            console.log('已断开连接');
        }, 5000);
        
    } catch (error) {
        console.error('错误:', error);
    }
}

// 导出客户端类
module.exports = ChatClient;

// 如果直接运行此文件，则执行示例
if (require.main === module) {
    example();
} 